import { Client } from '@stomp/stompjs';
import { getToken } from '@/utils/auth';

class PollingService {
  private client: Client | null = null;
  private reconnectAttempts = 0;
  private maxReconnectAttempts = 5;
  private reconnectDelay = 3000;

  private pollingInterval: number | null = null;
  private pollingDelay = 30000; // 30秒轮询一次

  // 回调函数
  private onLiteratureStatusUpdate: ((literatureId: number) => void) | null = null;
  private onChartUpdate: (() => void) | null = null;

  // 设置回调函数
  public setOnLiteratureStatusUpdate(callback: (literatureId: number) => void) {
    this.onLiteratureStatusUpdate = callback;
  }

  public setOnChartUpdate(callback: () => void) {
    this.onChartUpdate = callback;
  }

  // 开始轮询
  public startPolling() {
    // 清除现有的轮询
    if (this.pollingInterval) {
      clearInterval(this.pollingInterval);
    }

    console.log('开始轮询服务');
    
    // 立即执行一次
    this.poll();
    
    // 设置定时轮询
    this.pollingInterval = window.setInterval(() => {
      this.poll();
    }, this.pollingDelay);
  }

  // 轮询函数
  private async poll() {
    try {
      // 这里可以调用API检查是否有更新
      // 为了简化实现，我们直接触发更新回调
      if (this.onChartUpdate) {
        this.onChartUpdate();
      }
      
      console.log('轮询检查完成');
    } catch (error) {
      console.error('轮询检查失败:', error);
    }
  }

  // 停止轮询
  public stopPolling() {
    if (this.pollingInterval) {
      clearInterval(this.pollingInterval);
      this.pollingInterval = null;
      console.log('轮询服务已停止');
    }
  }

  // 连接到WebSocket服务器
  public connect() {
    if (this.client && this.client.connected) {
      console.log('WebSocket已经连接');
      return;
    }

    // 获取认证token
    const token = getToken();
    if (!token) {
      console.error('未找到认证token，无法建立WebSocket连接');
      return;
    }

    console.log('尝试连接WebSocket服务器，token:', token);

    // 使用原生WebSocket而不是SockJS，避免global is not defined错误
    this.client = new Client({
      brokerURL: 'ws://localhost:10003/document-service/ws',
      // 添加认证头
      connectHeaders: {
        Authorization: `Bearer ${token}`
      },
      reconnectDelay: this.reconnectDelay,
      heartbeatIncoming: 4000,
      heartbeatOutgoing: 4000,
      // 使用原生WebSocket
      webSocketFactory: () => {
        console.log('创建WebSocket连接到: ws://localhost:10003/document-service/ws');
        return new WebSocket('ws://localhost:10003/document-service/ws');
      },
      onConnect: () => {
        console.log('WebSocket连接成功');
        this.reconnectAttempts = 0;
        this.subscribeToTopics();
      },
      onDisconnect: () => {
        console.log('WebSocket断开连接');
      },
      onStompError: (frame) => {
        console.error('STOMP错误:', frame);
      },
      onWebSocketClose: () => {
        console.log('WebSocket连接关闭');
        this.handleReconnect();
      },
      onWebSocketError: (error) => {
        console.error('WebSocket错误:', error);
      }
    });

    this.client.activate();
  }

  // 订阅主题
  private subscribeToTopics() {
    if (!this.client || !this.client.connected) {
      console.log('WebSocket未连接，无法订阅主题');
      return;
    }

    console.log('开始订阅WebSocket主题');

    // 订阅文献状态更新
    this.client.subscribe('/topic/literature-status', (message) => {
      console.log('收到文献状态更新消息:', message.body);
      if (this.onLiteratureStatusUpdate) {
        try {
          const literatureId = parseInt(message.body);
          this.onLiteratureStatusUpdate(literatureId);
        } catch (error) {
          console.error('处理文献状态更新消息失败:', error);
        }
      }
    });

    // 订阅图表更新
    this.client.subscribe('/topic/chart-update', (message) => {
      console.log('收到图表更新消息:', message.body);
      if (this.onChartUpdate) {
        this.onChartUpdate();
      }
    });

    console.log('已订阅WebSocket主题');
  }

  // 处理重连
  private handleReconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
      
      setTimeout(() => {
        this.connect();
      }, this.reconnectDelay);
    } else {
      console.error('达到最大重连次数，停止重连');
    }
  }

  // 断开连接
  public disconnect() {
    if (this.client) {
      this.client.deactivate();
      console.log('WebSocket连接已断开');
    }
  }

  // 模拟发送文献状态更新通知的方法（用于文献识别完成后调用）
  public simulateLiteratureStatusUpdate(literatureId: number) {
    console.log('模拟文献状态更新通知，文献ID:', literatureId);
    if (this.onLiteratureStatusUpdate) {
      this.onLiteratureStatusUpdate(literatureId);
    }
  }

  // 模拟发送图表数据更新通知的方法（用于文献识别完成后调用）
  public simulateChartUpdate() {
    console.log('模拟图表数据更新通知');
    if (this.onChartUpdate) {
      this.onChartUpdate();
    }
  }

  // 检查连接状态
  public isConnected(): boolean {
    return this.client !== null && this.client.connected;
  }
}

// 创建单例实例
const pollingService = new PollingService();
export default pollingService;
